<?php

	namespace model;

		require_once ("User.php");

		class Session
		{
			/**
			* @param  Session $session
			*/					
			public function validateSession(Session $session)
			{				
				$pageView = new \view\HTMLPageView();
				$loginPageView = new \view\HTMLloginView();

				/**
				 * If user is logged in with cookie TODO - Validate cookies
				 */				 
				if (isset($_COOKIE["Name"]) && isset($_COOKIE["Password"]))
				{					
					$validateCookieData = unserialize(file_get_contents("cookieExpireTime.txt"));
										
					if (($_COOKIE["Name"]) == $validateCookieData["Name"] && ($_COOKIE["Password"]) == $validateCookieData["Password"] && time() < $validateCookieData["ExpireTime"]) 
					{
						echo $loginPageView->getLoginPage
						("Du är inloggad med hjälp av kakor som ", $_COOKIE["Name"], "Inloggad");
					}					
					else
					{
						//TODO throw new \Exception("KAKA!!! FEL");
						echo $pageView->getPage
						("TRAMSA INTE MED KAKORNA!", "Ej Inloggad", null);
						setcookie("Name", "", time() - 3600);
						setcookie("Password", "", time() - 3600);
					}
				}

				if (!isset($_SESSION["thisSession"]))
				{										
					$this->setUserSession();														
				}
				
				else if (isset($_SESSION["thisSession"]))
				{
					/**
				 	* If browswer or ip address are incorrect 
					*/		
					if ($_SESSION["thisSession"]["sessionBrowser"] != $_SERVER['HTTP_USER_AGENT'])
					{
						echo $pageView->getPage
						("Tramsa inte med kakorna i olika browsers!", "Ej Inloggad", null);
					}
					if ($_SESSION["thisSession"]["sessionIp"] != $_SERVER['REMOTE_ADDR'])
					{
						echo $pageView->getPage
						("Tramsa inte med kakornas ip-adress!", "Ej Inloggad", null);
					}	
					/**
				 	* If user is logged in with session
					*/					
					if (isset($_SESSION["thisSession"]["session_password"]) && isset($_SESSION["thisSession"]["session_name"]))
					{
						echo $loginPageView->getLoginPage
						("Du är inloggad via sessionen ", $_SESSION["thisSession"]["session_name"], "Inloggad");						
					}		
				}
				else
				{
					header("Location: labb2.php");
				}
			}
			/**
			 * @param String $userName
			 * @param String $userPassW
			 */
			public function setSession($userName, $userPassW)
			{
				$_SESSION["thisSession"] = array();
				$_SESSION["thisSession"]["sessionBrowser"] = $_SERVER['HTTP_USER_AGENT'];
				$_SESSION["thisSession"]["sessionIp"] = $_SERVER['REMOTE_ADDR'];
				$_SESSION["thisSession"]["session_name"] = $userName;
				$_SESSION["thisSession"]["session_password"] = $userPassW;

			}
			public function setUserSession()
			{
				$_SESSION["thisSession"] = array();
				$_SESSION["thisSession"]["sessionBrowser"] = $_SERVER['HTTP_USER_AGENT'];
				$_SESSION["thisSession"]["sessionIp"] = $_SERVER['REMOTE_ADDR'];
			}
		}
